package com.zydl.f9164m.fragment.passageway;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.clj.fastble.utils.BleLog;
import com.suke.widget.SwitchButton;
import com.zydl.f9164m.R;
import com.zydl.f9164m.basis.BasisFragment;
import com.zydl.f9164m.bean.ParamListData;
import com.zydl.f9164m.util.EditTextUtil;
import com.zydl.f9164m.util.PassWayUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * to handle interaction events.
 * Use the {@link RSParamFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class RSParamFragment extends BasisFragment {

    private String hardwareInterface;
    private List<ParamListData> passWayList;

    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;
    MyAdapter adapter;
    ArrayList<ParamListData> showList = new ArrayList<>();

    public static RSParamFragment newInstance() {
        RSParamFragment fragment = new RSParamFragment();
        return fragment;
    }

    public static RSParamFragment newInstance(String hardwareInterface, List<ParamListData> passWayList) {
        RSParamFragment fragment = new RSParamFragment();
        fragment.hardwareInterface = hardwareInterface;
        fragment.passWayList = passWayList;
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    @Override
    public void initViews() {
        super.initViews();
        setContentView(R.layout.fragment_rsparam);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new MyAdapter();
        recyclerView.setAdapter(adapter);
    }


    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
//        EditTextUtil.setEditTextInhibitInputSpeChat(deviceAdd);
        readData(hardwareInterface,passWayList);
    }


    //回读
    public void readData(String hardwareInterface, List<ParamListData> passWayList) {
        if (!TextUtils.isEmpty(hardwareInterface) && passWayList.size()>1&& isAdded()) {
            showList.clear();
            PassWayUtil.hardwareInterfaceIsChange(hardwareInterface,passWayList);
            switch (hardwareInterface){
                case "RS485-1":
                case "RS485-2":
                case "RS485-3":
                case "RS232-1":
                case "LORA":
                    for (ParamListData data : passWayList){
                        switch (data.getName()){
                            case "通信波特率":
                            case "数据位":
                            case "停止位":
                            case "校验位":
                            case "总线通信模式":
                            case "设备地址":
                            case "功能码":
                            case "寄存器地址":
                            case "寄存器个数":
                            case "数据截取":
                            case "通用串口":
                                showList.add(data);
                                break;
                        }
                    }
                    break;
                case "ADC0":
                case "ADC1":
                    for (ParamListData data : passWayList){
                        switch (data.getName()){
                            case "ADC类型":
                            case "上量程":
                            case "下量程":
                            case "最大值":
                            case "最小值":
                                showList.add(data);
                                break;
                        }
                    }
                    break;
            }

            adapter.notifyDataSetChanged();
            recyclerView.setAdapter(adapter);
        }
    }



    public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

        public MyAdapter() {

        }

        //创建新View，被LayoutManager所调用
        @Override
        public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.fragment_pass_way_base_item, viewGroup, false);
            return new MyAdapter.ViewHolder(view);
        }


        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(MyAdapter.ViewHolder viewHolder, int position) {
            viewHolder.list_item.setTag(position);
            viewHolder.bind(position);
        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            return showList == null ? 0 : showList.size();
        }


        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {

            @BindView(R.id.list_item)
            LinearLayout list_item;
            @BindView(R.id.tv_name)
            TextView tvName;
            @BindView(R.id.edit_text)
            EditText editText;
            @BindView(R.id.img_spanner)
            ImageView imgSpanner;
            @BindView(R.id.tv_unit)
            TextView tvUnit;
            @BindView(R.id.tv_synchro)
            TextView tvSynchro;
            @BindView(R.id.switch_btn)
            SwitchButton switchBtn;

            public ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
            }


            public void bind(int position) {
                ParamListData terminalListData = showList.get(position);
                tvName.setText(terminalListData.getName());
                switch (terminalListData.getType()) {
                    case 1: //spinner
                        editText.setText("" + (TextUtils.isEmpty(terminalListData.getValue()) ? terminalListData.getKey() : terminalListData.getValue()));
                        editText.setHint("请选择" + terminalListData.getName());
                        editText.setEnabled(terminalListData.isEnable());
                        imgSpanner.setVisibility(View.VISIBLE);
                        if(!TextUtils.isEmpty(terminalListData.getUnit())){
                            tvUnit.setVisibility(View.VISIBLE);
                            tvUnit.setText(terminalListData.getUnit());
                        }else {
                            tvUnit.setVisibility(View.GONE);
                        }
                        switchBtn.setVisibility(View.GONE);
                        tvSynchro.setVisibility(View.GONE);
                        list_item.setBackgroundResource(R.color.white);
                        break;
                    case 2:  // edit
                        editText.setText("" + terminalListData.getValue());
                        editText.setEnabled(terminalListData.isEnable());
                        editText.setVisibility(View.VISIBLE);

                        if(terminalListData.isEnable()){
                            editText.setHint("请输入" + terminalListData.getName());
                            list_item.setBackgroundResource(R.color.white);
                        }else {
                            list_item.setBackgroundResource(R.color.inputbg);
                        }
                        tvUnit.setVisibility(View.VISIBLE);
                        tvUnit.setText(terminalListData.getUnit());
                        imgSpanner.setVisibility(View.GONE);
                        switchBtn.setVisibility(View.GONE);
                        tvSynchro.setVisibility(View.GONE);

                        break;
                }
                editText.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        int curPosition = getAdapterPosition();
                        ParamListData data = showList.get(curPosition);
                        data.setChange(true);
                        data.setValue(s.toString());
                    }
                });

                imgSpanner.setTag(terminalListData);
                tvSynchro.setTag(terminalListData);
            }

            @OnClick(R.id.img_spanner)
            public void showSpanner(View v) {
                final ParamListData terminalListData = (ParamListData) v.getTag();
                OptionsPickerView pickerView = new OptionsPickerBuilder(mContext, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        editText.setText(terminalListData.getValues().get(options1));
                        if(terminalListData.getName().equals("总线通信模式")){
                            changeAdapter(editText.getText().toString().trim());
                        }
                    }
                })
                        .setSubmitText("确定")//确定按钮文字
                        .setCancelText("取消")//取消按钮文字
                        .build();
                pickerView.setPicker(terminalListData.getValues());
                pickerView.show();
            }
        }
    }


    private void changeAdapter(String dataValue){
        for (int i = 0;i<showList.size();i++){
            ParamListData data = showList.get(i);
            if(data.getName().equals("设备地址") || data.getName().equals("功能码") || data.getName().equals("寄存器地址") || data.getName().equals("寄存器个数") || data.getName().equals("数据截取")|| data.getName().equals("通用串口")){
                switch (dataValue){
                    case "透传":
                        data.setEnable(false);
                        break;
                    case "串口":
                        if(!data.getName().equals("通用串口")){
                            data.setEnable(false);
                        }else {
                            data.setEnable(true);
                        }
                        break;
                    case "MODBUS":
                    case "MODBUS_FLOAT":
                    case "MODBUS_BCD":
                        if(data.getName().equals("通用串口")){
                            data.setEnable(false);
                        }else {
                            data.setEnable(true);
                        }
                        break;
                }

                int position = i;
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        // 刷新操作
                        adapter.notifyItemChanged(position);
                    }
                });

            }

        }

    }
}
